"""DcmConvertWithSlicer.py

    此代码直接封装Slicer的导入DCM文件的流程, 偏临时
    输入是一个Json文件，包含输入文件列表，转出文件存放位置

    后面将尝试以下一些步骤:
        1. 拆分vtkITK模块，尝试分离vtkITK模块，让常规python可以执行不经过Slicer
        2. 二次编译源码，或者使用Python重新实现算法模块，以达到完全的可控性
"""
import sys
import json
import logging
import time

import slicer

logging.error(sys.argv)  # 输出被Slicer拦截，无法在传统控制台看到

if len(sys.argv) > 1:
    json_file = sys.argv[1]
    if json_file is None or json_file == "":
        logging.error("无输入的json文件")
        sys.exit(-1)
else:
    sys.exit(-1)

try:
    with open(json_file, "r", encoding='utf-8') as f:
        json_data = json.load(f)
except Exception as e:
    logging.error("Json读取异常")
    sys.exit(-1)

plugins = slicer.modules.dicomPlugins['DICOMScalarVolumePlugin']()

keys = list(json_data.keys())
for index in range(len(keys)):
    each_key = keys[index]
    data_d = json_data[each_key]
    files = data_d["files"]
    output = data_d["output"]
    format = data_d["format"]  # DCMTK GDCM

    try:
        node = plugins.loadFilesWithSeriesReader(format, files, "reader")
        slicer.util.saveNode(node, output)
        slicer.mrmlScene.RemoveNode(node)
        logging.warning("Done {}, Now: {}%".format(each_key, (index + 1) / len(keys) * 100))
        slicer.app.processEvents()
    except Exception as e:
        logging.error(str(e))

time.sleep(3)
slicer.util.exit()
